package com.uphone.kingmall.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.uphone.kingmall.base.BaseTabActivity;
import com.uphone.kingmall.fragment.GoodsListFragment;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.intent.IntentData;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/19
 *     desc   :
 * </pre>
 */
public class HomeCatListActivity extends BaseTabActivity implements AMapLocationListener {


    @Override
    protected void selectChange(boolean selected) {
        if (fragmentList != null) {
            int currentItem = viewPager.getCurrentItem();
            if (currentItem >= 0 && currentItem < fragmentList.size()) {
                if (fragmentList.get(currentItem) instanceof GoodsListFragment) {
                    ((GoodsListFragment) fragmentList.get(currentItem)).reload(selected, 1);
                }
            }
        }

    }

    @IntentData
    int id = -1;
    @IntentData
    String title = "商品列表";
    @IntentData
    String url = "";
    private List<Fragment> fragmentList;

    @Override
    protected String initTitle() {
        loadPermission();
        return title;
    }

    @Override
    protected List<Fragment> getFragmentList() {
        fragmentList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            fragmentList.add(GoodsListFragment.newInstance(i + 1, id, GoodsListFragment.TYPE_CRICLE_CAT, url));
        }
        return fragmentList;
    }

    @Override
    protected String[] getItems() {
        return new String[]{"综合排序", "销量优先", "好评优先", "距离最近"};
    }

    private String city;
    private LatLng latLng;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private static final int PERMISSION_REQUEST_MY_REQUEST = 3;

    private void loadPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(HomeCatListActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(HomeCatListActivity.this, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_SETTINGS);
            }
            if (ContextCompat.checkSelfPermission(HomeCatListActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (!permissionList.isEmpty()) {  //申请的集合不为空时，表示有需要申请的权限
                requestPermissions(permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQUEST_MY_REQUEST);
            } else { //所有的权限都已经授权过了
                initLocation();
            }
        } else {
            initLocation();
        }

    }

    /**
     * 如果AMapLocationClient是在当前Activity实例化的，
     * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(HomeCatListActivity.this);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                LogUtils.e("定位信息：", aMapLocation.getLatitude(), aMapLocation.getLongitude(), aMapLocation.getCity());
                city = aMapLocation.getCity();
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mLocationClient.stopLocation();
                if (fragmentList != null) {
                    for (int i = 0; i < fragmentList.size(); i++) {
                        if (fragmentList.get(i) instanceof GoodsListFragment) {
                            ((GoodsListFragment) fragmentList.get(i)).reload(city, latLng, 1);
                        }
                    }
                }
            }
        } else {
            LogUtils.e("定位失败");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            if (requestCode == PERMISSION_REQUEST_MY_REQUEST) {
                // 定位权限
                if (ContextCompat.checkSelfPermission(HomeCatListActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有开启定位权限，定位失败");
                    DialogUtil.openAppDetails(HomeCatListActivity.this, "定位");
                }
            }
        }
    }
}
